package com.onepiece.shipelves.common.utils;

import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.jcajce.provider.symmetric.AES;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.security.Security;


/**
 * @author: ting
 * @date: 2019-08-12
 */
public class AESPKCS7Util {

    static {
        Security.addProvider(new BouncyCastleProvider());
    }

    public final static String AES = "AES/ECB/PKCS7Padding";

    public final static String CRYPT_KEY = "WTAHAPPYACTIVITY";

    public final static String ENCRYPT_CHARSET = "UTF-8";


    public static void main(String[] args) throws Exception {
        String content = "hello World";
        String password = "151";
        System.out.println("原内容：\n"+content);
        String tempContent = encrypt(content,CRYPT_KEY);
        System.err.println("加密后：\n"+tempContent);
        tempContent = decrypt(tempContent, CRYPT_KEY);
        System.out.println("解密后：\n"+tempContent);
    }

    /**
     * encrypt input text
     *
     * @param input
     * @param key
     * @return
     */
    public static String encrypt(String input, String key) {
        byte[] crypted = null;
        try {

            SecretKeySpec skey = new SecretKeySpec(key.getBytes(), "AES");

            Cipher cipher = Cipher.getInstance(AES);
            cipher.init(Cipher.ENCRYPT_MODE, skey);
            crypted = cipher.doFinal(input.getBytes());
        } catch (Exception e) {
            System.out.println(e.toString());
            e.printStackTrace();
        }

        return new String(Base64.encodeBase64(crypted));
    }

    /**
     * decrypt input text
     *
     * @param input
     * @param key
     * @return
     */
    public static String decrypt(String input, String key) {
        byte[] output = null;
        try {
            SecretKeySpec skey = new SecretKeySpec(key.getBytes(), "AES");
            Cipher cipher = Cipher.getInstance(AES);
            cipher.init(Cipher.DECRYPT_MODE, skey);
            output = cipher.doFinal(Base64.decodeBase64(input));
        } catch (Exception e) {
            System.out.println(e.toString());
        }
        return new String(output);
    }
}
